<?php

declare (strict_types = 1);

namespace app\store\service\statistics\data;

use app\common\enum\order\PayStatus;
use app\common\enum\user\balanceLog\Scene;
use app\common\library\helper;
use app\common\service\BaseService;
use app\store\model\OrderGoods;
use app\store\model\User as UserModel;
use app\store\model\Order as OrderModel;
use app\common\enum\order\PayStatus as PayStatusEnum;
use app\store\model\user\BalanceLog;


/**
 * 数据概况
 * Class Survey
 * @package app\store\service\statistics\data
 */
class Survey extends BaseService
{
    /**
     * 获取数据概况
     * @param null $startDate
     * @param null $endDate
     * @return array
     */
    public function getSurveyData($startDate = null, $endDate = null): array
    {
        $orderTotalPrice =  (float)$this->getOrderTotalPrice($startDate, $endDate);
        $orderTotalPrice = sprintf("%0.2f",$orderTotalPrice);
        return [
            // 用户数量
            'userTotal' => $this->getUserTotal($startDate, $endDate),
            // 消费人数
            'consumeUsers' => $this->getConsumeUsers($startDate, $endDate),
            // 支付订单数
            'orderTotal' => $this->getOrderTotal($startDate, $endDate),
            // 总销售额(元)
            'orderTotalPrice' => $orderTotalPrice,
            // 平台销售额(元)
            'platformOrderTotalPrice' => $this->getOrderTotalPrice($startDate, $endDate),
            // 商品总量
            'goodsTotal' => $this->getGoodsTotal($startDate, $endDate),
            // 用户充值总额
            'rechargeTotalMoney' => 0,
            //用户总利润
            "userTotalProfit" => $this->getUserTotalProfit($startDate, $endDate),
        ];
    }

    /**获取用户总利润
     * @param $startDate
     * @param $endDate
     * @return string
     */
    public function getUserTotalProfit($startDate, $endDate):string
    {
        return '';
    }






    /**
     * 获取用户总量
     * @param null $startDate
     * @param null $endDate
     * @return string
     */
    private function getUserTotal($startDate = null, $endDate = null)
    {
        // 检索查询条件
        $filter = [];
        if (!is_null($startDate) && !is_null($endDate)) {
            $filter[] = ['created_at', '>=', $startDate];
            $filter[] = ['created_at', '<', date('Y-m-d H:i:s',strtotime($endDate) + 86400)];
        }
        // 查询总记录
        $value = (new UserModel)->where($filter)
            ->where('is_delete', '=', '0')
            ->count();
        return number_format($value);
    }

    /**
     * 消费人数
     * @param null $startDate
     * @param null $endDate
     * @return string
     */
    public function getConsumeUsers($startDate = null, $endDate = null)
    {
        // 检索查询条件
        $filter = [];
        if (!is_null($startDate) && !is_null($endDate)) {
            $filter[] = ['pay_time', '>=', strtotime($startDate)];
            $filter[] = ['pay_time', '<', strtotime($endDate) + 86400];
        }
        // 查询总记录
        $value = (new OrderModel)->field('user_id')
            ->where($filter)
            ->where('pay_status', '=', PayStatusEnum::SUCCESS)
            //  ->where('order_status', '<>', OrderStatusEnum::CANCELLED)
            ->where('is_delete', '=', '0')
            ->group('user_id')
            ->count();
        return number_format($value);
    }

    /**
     * 获取订单总量
     * @param null $startDate
     * @param null $endDate
     * @return string
     */
    private function getOrderTotal($startDate = null, $endDate = null)
    {
        return number_format((new OrderModel)->getPayOrderTotal($startDate, $endDate));
    }

    /**
     * 付款订单总额
     * @param null $startDate
     * @param null $endDate
     * @return string
     */
    private function getOrderTotalPrice($startDate = null, $endDate = null)
    {
        return helper::number2((new OrderModel)->getOrderTotalPrice($startDate, $endDate));
    }

    /**
     * 获取订单商品总量
     * @param null $startDate
     * @param null $endDate
     * @return string
     */
    private function getGoodsTotal($startDate = null, $endDate = null): int
    {
        // 检索查询条件
        $filter = [];
        if (!is_null($startDate) && !is_null($endDate)) {
            $filter[] = ['created_at', '>=', $startDate];
            $filter[] = ['created_at', '<', date('Y-m-d H:i:s',strtotime($endDate) + 86400)];
        }
        // 查询总记录
        $value = (new OrderGoods())->where($filter)->sum('total_num');
        return intval($value);
    }




    /**赏箱排行榜--注意要加上预存卡金额
     * @return array
     */
    public function getLuckyBagSale():array
    {
        $condition1 = [
            ['toy_order.pay_status','=',PayStatus::SUCCESS],
            ['toy_order.order_lucky_type','IN',[RaffleType::LIMITED_POOL,RaffleType::ENDLESS_POOL,RaffleType::BOX_EXTRACTOR]],
        ];
        $condition2 = [
            ['toy_order.pay_status','=',PayStatus::SUCCESS],
            ['toy_order.order_lucky_type','IN',[RaffleType::LIMITED_POOL,RaffleType::ENDLESS_POOL,RaffleType::BOX_EXTRACTOR]],
            ['toy_user_coupon.coupon_type','=',CouponType::PRE_STORAGE_CARD]
        ];
        $order_list = OrderModel::where($condition1)
            ->field("toy_order.activity_id,toy_lucky_bag_activity.name,SUM(toy_order.pay_price) as gprice")
            ->join('toy_lucky_bag_activity','toy_lucky_bag_activity.activity_id = toy_order.activity_id','left')
            ->group('toy_order.activity_id')
            ->select()
            ->toArray();
        $order_pre_card_money_list =  OrderModel::where($condition2)
            ->field("toy_order.activity_id,SUM(toy_order.coupon_money) as total_coupon_money")
            ->join('toy_user_coupon','toy_user_coupon.user_coupon_id = toy_order.coupon_id','left')
            ->group('toy_order.activity_id')
            ->select()
            ->toArray();
        $tmp = [];
        if(!empty($order_pre_card_money_list)){
            foreach ($order_pre_card_money_list as $val){
                $tmp[$val['activity_id']] = $val;
            }
        }
        //dd($order_list,$order_pre_card_money_list);
       foreach ($order_list as &$item){
           $item['pre_card_money'] = $tmp[$item['activity_id']]['total_coupon_money'] ?? 0;
           $item['gprice'] += $item['pre_card_money'];
           $sale = LuckyBag::where('activity_id',$item['activity_id'])->value('sale');
           $item['total_sales_num'] = $sale ?? 0;
       }

        // 总销售额
        array_multisort(array_column($order_list,'gprice'),SORT_DESC,$order_list);
        return array_slice($order_list,0,10);

    }

}
